# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from users.models import UserModel
from django.http import HttpResponse
import re,string,requests
import random,time,json
from random import randint

from celery_tasks.sms_code.tasks import send_message
from datetime import datetime
from utils.my_redis import r
from django.contrib.auth.hashers import check_password,make_password

# 注册
from django.conf import settings
# settings.configure(DEBUG=True) # 声明


from captcha.image import ImageCaptcha
class Imgcode(APIView):
    def get(self,request,uuid):
        code= ''.join(random.sample(string.ascii_letters + string.digits, 4))
        cap = ImageCaptcha()
        img_code = cap.generate(code)
        r.set_str(uuid,code,120)
        return HttpResponse(img_code,content_type='image/png')




class SendSmsCode(APIView):
    def get(self,request):
        mobile = request.GET.get('mobile')
        img_code = request.GET.get('img_code')
        uuid = request.GET.get('uuid')
        if not all([mobile,img_code,uuid]):
            return Response({'code': 401, 'msg': '信息不完整'})
        r_code = r.get_str(uuid)
        if not r_code:
            return Response({'code': 401, 'msg': '图片验证码过期'})

        print(r_code)
        if img_code.lower() != r_code.decode().lower():
            return Response({'code': 401, 'msg': '图片验证码错误'})
        data = randint(100000, 999999)
        resp = send_message(mobile,data)
        print('resp>>>',resp,type(resp)) # resp:json字典
        if resp:
            # 短信发送成功后，写入redis便于后边校验
            r.set_str('sms_%s'%mobile,data,600)
            return Response({'msg':'发送成功','code':200,'data':data})
        else:
            return Response({'msg':'发送失败','code':500})


class Register(APIView):
    def post(self,request):
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        user_type = int(request.data.get('user_type'))
        code = request.data.get('code')
        new_code = r.get_str('sms_%s' % mobile)
        if not all([password,mobile,code]):
            return Response({'code': 204, 'msg': '信息不完整'})
        if not re.findall(r'^1[3-9]\d{9}$', mobile):
            return Response({'code': 204, 'msg': '手机号格式错误'})
        if UserModel.objects.filter(mobile=mobile):
            return Response({'code': 400, 'msg': '手机号重复'})
        if new_code.decode()!=code:
            return Response({"code": 400, "msg": "验证码错误"})
        s = datetime.strftime(datetime.now(), "%m%d")
        n = s + mobile[-4:]
        username='用户_'+n
        new_pwd = make_password(password)
        UserModel.objects.create(username=username,password=new_pwd,mobile=mobile,user_type=user_type)
        return Response({'code': 200, 'msg': '注册完成'})

